﻿using System;
using Eneta.Portal.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Companies
{
    public class ListFeatureReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var web = properties.Feature.Parent as SPWeb;
            if (web == null)
                web = ((SPSite)properties.Feature.Parent).RootWeb;

            if (!PublishingWeb.IsPublishingWeb(web))
                throw new Exception("Current web is not publishing web!");

            web.AllowUnsafeUpdates = true;

            var pagesListName = PublishingWeb.GetPagesListName(web);
            var pagesList = web.Lists[pagesListName];
            var list = web.Lists["IOCompany"];

            if (list.HasField("Company"))
                return;

            list.Fields.AddLookup("Company", pagesList.ID, true);
            var field = list.Fields["Company"] as SPFieldLookup;
            field.LookupField = SPBuiltInFieldId.Title.ToString();
            field.Update(true);
            list.Update();


        }
    }
}
